﻿using MediatR;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using Return.Enum;
using SlaughterItem.Common.Infrastructures.Interfaces;
using System.Globalization;
using THE_WIND_RISES.Common.Domans.Produce.Supplier;
using THE_WIND_RISES.Common.Dtos;

namespace Production_Set.API.Application.Commands.Supplier
{
    public class SuppliersImportHandler : IRequestHandler<SuppliersImportCommand, Result>
    {
        /// <summary>
        /// 供应商仓储
        /// </summary>
        private readonly IBaseRepository<SuppliersDto> supplierRepository;
        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<SuppliersImportHandler> logger;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="supplierRepository"></param>
        public SuppliersImportHandler(IBaseRepository<SuppliersDto> supplierRepository, ILogger<SuppliersImportHandler> logger)
        {
            this.supplierRepository = supplierRepository;
            this.logger = logger;
        }
        public async Task<Result> Handle(SuppliersImportCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var result = new Result() { Code = (int)CommonErrorCodes.Search };

                //获取文件扩展名 判断上传的文件类型是否正确
                var ext = Path.GetExtension(request.file.FileName);
                if (ext == ".xls" || ext == ".xlsx")
                {

                }
                else
                {
                    result.Msg = "您上传的文件类型不正确";
                }


                using (MemoryStream ms = new MemoryStream())
                {
                    request.file.CopyTo(ms);
                    ms.Position = 0;



                    //根据文件扩展名创建对应的工作簿对象(HSSFWorkbook用于.xls,XSSFWorkbook用于.xlsx)

                    //获取工作簿
                    IWorkbook wb = null;

                    if (ext == ".xls")//创建97-2003
                    {
                        wb = new HSSFWorkbook(ms);
                    }
                    else//创建2007及以上版本
                    {
                        wb = new XSSFWorkbook(ms);
                    }

                    //获取sheet 获取工作簿中的第一个工作表
                    ISheet sheet = wb.GetSheetAt(0);

                    int totalRows = sheet.LastRowNum;//总行数
                    int totalCells = sheet.GetRow(0).LastCellNum;//总列数

                    //创建一个用于存储解析后的数据的列表
                    var SupplierList = new List<SuppliersDto>();

                    //循环总行数 开头必须是1 不然从表头开始
                    //遍历工作表的每一行(从第二行开始,因为第一行通常是表头)

                    for (int i = 1; i <= totalCells; i++)
                    {
                        //获取当前行
                        IRow row = sheet.GetRow(i);

                        //这个类必须写到循环里面 不然批量添加只能添加一行
                        var dto = new SuppliersDto();

                        if (row == null) continue;//跳过空行

                        //dto.SuppliersId = Convert.ToInt32(row.GetCell(0).ToString());
                        dto.SuppliersNo = row.GetCell(1).ToString();
                        dto.SuppliersName = row.GetCell(2).ToString();
                        dto.SuppliersType = row.GetCell(3).ToString();
                        dto.SuppliersPhone = row.GetCell(4).ToString();
                        dto.SuppliersAdder = row.GetCell(5).ToString();
                        dto.CountryId = Convert.ToInt32(row.GetCell(6).ToString());
                        dto.CityId = Convert.ToInt32(row.GetCell(7).ToString());
                        dto.SupplierClassification = row.GetCell(8).ToString();
                        dto.SupplierLabels = row.GetCell(9).ToString();
                        dto.CompanyLogo = row.GetCell(10).ToString();
                        dto.OutsideLabel = Convert.ToInt32(row.GetCell(11).ToString());
                        dto.SuppliersStatus = Convert.ToInt32(row.GetCell(12).ToString());
                        dto.IsDelete = Convert.ToInt32(row.GetCell(13).ToString());
                        dto.Handle = row.GetCell(14).ToString();
                        dto.HandleContext = row.GetCell(15).ToString();
                        //日期转换
                        //日期在excel表中必须是年月日格式 但不能加时分秒 (注意!!!!)
                        string inputDate = row.GetCell(16).ToString();
                        string[] multipleFormats = { "dd-M月-yyyy", "yyyy-M-dd" };
                        DateTime parsedDate;
                        foreach (var format in multipleFormats)
                        {
                            if (DateTime.TryParseExact(inputDate, new[] { format }, CultureInfo.InvariantCulture, DateTimeStyles.None, out parsedDate))
                            {
                                dto.HandleTime = parsedDate;
                                break;//成功解析后跳出循环
                            }
                        }
                        dto.Pid = Convert.ToInt32(row.GetCell(17).ToString());
                        //添加到数据集合中
                        SupplierList.Add(dto);
                    }


                    //跳出循环后 使用 AddRange进行批量添加
                    string sql = "insert into Suppliers values(@SuppliersId,@SuppliersNo,@SuppliersName,@SuppliersType,@SuppliersPhone,@SuppliersAdder,@CountryId,@CityId,@SupplierClassification,@SupplierLabels,@CompanyLogo,@OutsideLabel,@SuppliersStatus,@IsDelete,@Handle,@HandleContext,@HandleTime,@Pid)";
                    var res = supplierRepository.AddRound(sql, SupplierList);
                    //判断
                    if (res > 0)
                    {
                        result.Code = (int)CommonErrorCodes.Success;
                        result.Msg = "导入成功";
                        logger.LogInformation("导入成功");
                    }
                    else
                    {
                        result.Msg = "导入失败";
                    }

                    return result;
                }
            }
            catch (Exception ex)
            {
                logger.LogError("导入失败" + ex.Message);
                throw;
            }

        }
    }
}
